package com.ckapi.ckapiclientsdk.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ckapi.ckapiclientsdk.model.Song;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.ckapi.ckapiclientsdk.utils.SignUtils.genSign;

public class CkApiClient {

    private static final String GATEWAY_HOST = "http://localhost:8090";

    private String accessKey;
    private String secretKey;

    public CkApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> map = new HashMap();
        map.put("sign", genSign(body, secretKey));
        try {
            body=URLEncoder.encode(body,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("accessKey", accessKey);
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("body", body);
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));

        return map;
    }

     public String getSong(Song song){
         String jsonParams = JSONUtil.toJsonPrettyStr(song);
         String result = HttpRequest.post(GATEWAY_HOST + "/api/song")
                 .addHeaders(getHeaderMap(jsonParams))
                 .body(jsonParams)
                 .execute().body();
         return result;
    }

    // 通用请求处理
    public String generalRequestHandling(String interfaceUrl,String method ,String  jsonParams){
        String result = "";
        if (method.equals("GET")){
            result = HttpRequest.get(GATEWAY_HOST + interfaceUrl)
                    .addHeaders(getHeaderMap(jsonParams))
                    .execute().body();
        }else{
            result = HttpRequest.post(GATEWAY_HOST + interfaceUrl)
                    .addHeaders(getHeaderMap(jsonParams))
                    .body(jsonParams)
                    .execute().body();
        }
        return result;
    }

}
